package com.wocai.jrt.orgadmin.stats.action;

import java.io.OutputStream;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.utils.common.ExportExcel;
import com.vteba.utils.date.DateUtils;
import com.vteba.web.action.GenericAction;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.employee.model.EmployeeGroup;
import com.wocai.jrt.orgadmin.employee.model.Org;
import com.wocai.jrt.orgadmin.employee.service.spi.OrgService;
import com.wocai.jrt.orgadmin.stats.bean.EmpStatsReqBean;
import com.wocai.jrt.orgadmin.stats.bean.EmpStatsResBean;
import com.wocai.jrt.orgadmin.stats.service.spi.EmployeeStatsService;
import com.wocai.jrt.orgadmin.stats.service.spi.GroupStatsJobService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

@Controller
@RequestMapping("/employeeStats")
public class EmployeeStatsAction extends GenericAction<EmployeeGroup> {
	private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeStatsAction.class);
	private static final String EMPLOYEE_STATS_REPORT = "理财师统计报表";

	@Inject
	private EmployeeStatsService employeeStatsServiceImpl;
	@Inject
	private OrgService orgServiceImpl;
	@Inject
	private GroupStatsJobService groupStatsJobServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 刷新缓存
	 * 
	 * @return
	 */
	@RequestMapping("/cache")
	public String cache() {
		groupStatsJobServiceImpl.groupStatsServiceCount();
		return "stats/employeeGroupStats/dayStats";
	}

	/**
	 * 跳转到按天统计页面
	 * 
	 * @return
	 */
	@RequestMapping("/day")
	public String day() {
		return "stats/employeeStats/dayStats";
	}

	/**
	 * 跳转到按月统计页面
	 * 
	 * @return
	 */
	@RequestMapping("/month")
	public String month() {
		return "stats/employeeStats/monthStats";
	}

	/**
	 * 跳转到按年统计页面
	 * 
	 * @return
	 */
	@RequestMapping("/year")
	public String year() {
		return "stats/employeeStats/yearStats";
	}

	/**
	 * 按日统计页面
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryDay")
	public Map<String, Object> queryDay(@RequestBody EmpStatsReqBean empStatsReqBean) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 默认的时间
			if (null == empStatsReqBean.getBeginDate() || null == empStatsReqBean.getEndDate()) {
				DateTime dateTime = new DateTime();
				empStatsReqBean.setBeginDate(dateTime.minusDays(6).toDate());
				empStatsReqBean.setEndDate(dateTime.toDate());
			}
			DateTime beginDateTime = new DateTime(empStatsReqBean.getBeginDate());
			DateTime endDateTime = new DateTime(empStatsReqBean.getEndDate());
			// 选择的时间超过一个月，前端限制了，后端再判断一下
			if (endDateTime.isAfter(beginDateTime.plusMonths(1))) {
				LOGGER.info("employeeStats querDay too much data!");
				return result;
			}
			LOGGER.info("employeeStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			// 查询数据
			List<EmpStatsResBean> empStatsList = employeeStatsServiceImpl.queryEmployeeStats(
					beginDateTime, endDateTime, empStatsReqBean.getStart(),
					empStatsReqBean.getPageSize());
			
			long totalRecord = employeeStatsServiceImpl.queryEmployeeStatsCount(beginDateTime, endDateTime);
			// jQuery datatable 就是这样的参数，阿西吧
			// result.put("sEcho", user.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
			result.put("aaData", empStatsList); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("employeeStats querDay error,msg = [{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 按月统计页面
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryMonth")
	public Map<String, Object> queryMonth(@RequestBody EmpStatsReqBean empStatsReqBean) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 默认的时间
			if (null == empStatsReqBean.getBeginDate() || null == empStatsReqBean.getEndDate()) {
				DateTime dateTime = new DateTime();
				empStatsReqBean.setBeginDate(dateTime.minusMonths(5).toDate());
				empStatsReqBean.setEndDate(dateTime.toDate());
			}
			DateTime beginDateTime = new DateTime(empStatsReqBean.getBeginDate());
			DateTime endDateTime = new DateTime(empStatsReqBean.getEndDate());
			// 选择的时间超过一年，前端限制了，后端再判断一下
			if (endDateTime.isAfter(beginDateTime.plusMonths(12))) {
				LOGGER.info("employeeStats querDay too much data!");
				return result;
			}
			LOGGER.info("employeeStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			// 查询数据
			List<EmpStatsResBean> empStatsList = employeeStatsServiceImpl.queryEmployeeStatsMonth(
					beginDateTime, endDateTime, empStatsReqBean.getStart(),
					empStatsReqBean.getPageSize());
			long totalRecord = employeeStatsServiceImpl.queryEmployeeStatsCount(beginDateTime, endDateTime);
			// jQuery datatable 就是这样的参数，阿西吧
			// result.put("sEcho", user.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
			result.put("aaData", empStatsList); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("employeeStats querDay error,msg = [{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 按年统计页面
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryYear")
	public Map<String, Object> queryYear(@RequestBody EmpStatsReqBean empStatsReqBean) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 默认的时间
			if (null == empStatsReqBean.getBeginDate() || null == empStatsReqBean.getEndDate()) {
				Org org = orgServiceImpl.get(UserUtils.getOrgId());
				empStatsReqBean.setBeginDate(org.getCreateTime());
				empStatsReqBean.setEndDate(new Date());
			}
			DateTime beginDateTime = new DateTime(empStatsReqBean.getBeginDate());
			DateTime endDateTime = new DateTime(empStatsReqBean.getEndDate());
			// //选择的时间超过一年，前端限制了，后端再判断一下
			// if (endDateTime.isAfter(beginDateTime.plusMonths(12))) {
			// LOGGER.info("employeeStats querDay too much data!");
			// return result;
			// }
			LOGGER.info("employeeStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			// 查询数据
			List<EmpStatsResBean> empStatsList = employeeStatsServiceImpl.queryEmployeeStatsMonth(
					beginDateTime, endDateTime, empStatsReqBean.getStart(),
					empStatsReqBean.getPageSize());
			long totalRecord = employeeStatsServiceImpl.queryEmployeeStatsCount(beginDateTime, endDateTime);
			// jQuery datatable 就是这样的参数，阿西吧
			// result.put("sEcho", user.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
			result.put("aaData", empStatsList); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("employeeStats querDay error,msg = [{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 报表下载
	 * 
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@ResponseBody
	@RequestMapping("/downloadReport")
	public void downloadReport(String startTime, String endTime, HttpServletResponse response) {
		try {
			// 默认的时间
			DateTime beginDateTime;
			DateTime endDateTime;
			if (null == startTime || null == endTime) {
				DateTime dateTime = new DateTime();
				beginDateTime = dateTime.minusDays(6);
				endDateTime = dateTime;
			} else {
				DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
				beginDateTime = DateTime.parse(startTime, formatter);
				endDateTime = DateTime.parse(endTime, formatter);
			}
			// 选择的时间超过一月，前端限制了，后端再判断一下
			if (endDateTime.isAfter(beginDateTime.plusMonths(1))) {
				LOGGER.info("employeeStats querDay too much data!");
				return;
			}
			LOGGER.info("employeeStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			// 查询数据
			List<EmpStatsResBean> empStatsList = employeeStatsServiceImpl.queryEmployeeStats(
					beginDateTime, endDateTime, null, null);
			List<Object[]> exportList = new ArrayList<Object[]>();
			for (EmpStatsResBean empStatsResBean : empStatsList) {
				NumberFormat nf = NumberFormat.getPercentInstance();
				nf.setMinimumFractionDigits(2);
				nf.setRoundingMode(RoundingMode.HALF_UP);
				DecimalFormat df = new DecimalFormat("#0.00");

				Object[] object = new Object[11];
				object[0] = empStatsResBean.getName();
				object[1] = empStatsResBean.getGroupName();
				object[2] = empStatsResBean.getInvestorNum();
				object[3] = empStatsResBean.getDealInvestorNum();
				object[4] = nf.format(empStatsResBean.getInvestorTurnRate());
				object[5] = empStatsResBean.getAppointmentNum();
				object[6] = empStatsResBean.getCheckinNum();
				object[7] = empStatsResBean.getOrdersNum();
				object[8] = df.format(empStatsResBean.getOrdersAmount() / 10000) + "万";
				object[9] = nf.format(empStatsResBean.getOrdersTurnRate());
				object[10] = df.format(empStatsResBean.getInvestorUnitPrice() / 10000) + "万";
				exportList.add(object);
			}
			String[] columns = { "理财师", "团队", "投资人数", "成交投资人数", "客户转化率", "预约数", "外勤签到数", "成交订单数",
					"销售额", "订单转化率", "客单价" };
			int[] columnWidths = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 };
			ExportExcel exportExcel = new ExportExcel(columns, true, exportList);
			exportExcel.setColumnWidths(columnWidths);
			Workbook workbook = exportExcel.toExcel();

			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream; charset=UTF-8");
			String fileName = EMPLOYEE_STATS_REPORT + DateUtils.toDateString("yyyyMMddHHmmss");
			response.setHeader("Content-Disposition",
					"attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
			OutputStream os = response.getOutputStream();
			workbook.write(os);
			os.flush();
			os.close();
			workbook.close();
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 报表下载
	 * 
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@ResponseBody
	@RequestMapping("/downloadReportMonth")
	public void downloadReportMonth(String startTime, String endTime, HttpServletResponse response) {
		try {
			// 默认的时间
			DateTime beginDateTime;
			DateTime endDateTime;
			if (null == startTime || null == endTime) {
				DateTime dateTime = new DateTime();
				beginDateTime = dateTime.minusMonths(6);
				endDateTime = dateTime;
			} else {
				DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM");
				beginDateTime = DateTime.parse(startTime, formatter);
				endDateTime = DateTime.parse(endTime, formatter);
			}
			// 选择的时间超过一年，前端限制了，后端再判断一下
			if (endDateTime.isAfter(beginDateTime.plusMonths(6))) {
				LOGGER.info("employeeStats querDay too much data!");
				return;
			}
			LOGGER.info("employeeStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			// 查询数据
			List<EmpStatsResBean> empStatsList = employeeStatsServiceImpl.queryEmployeeStatsMonth(
					beginDateTime, endDateTime, null, null);
			List<Object[]> exportList = new ArrayList<Object[]>();
			for (EmpStatsResBean empStatsResBean : empStatsList) {
				NumberFormat nf = NumberFormat.getPercentInstance();
				nf.setMinimumFractionDigits(2);
				nf.setRoundingMode(RoundingMode.HALF_UP);
				DecimalFormat df = new DecimalFormat("#0.00");

				Object[] object = new Object[11];
				object[0] = empStatsResBean.getName();
				object[1] = empStatsResBean.getGroupName();
				object[2] = empStatsResBean.getInvestorNum();
				object[3] = empStatsResBean.getDealInvestorNum();
				object[4] = nf.format(empStatsResBean.getInvestorTurnRate());
				object[5] = empStatsResBean.getAppointmentNum();
				object[6] = empStatsResBean.getCheckinNum();
				object[7] = empStatsResBean.getOrdersNum();
				object[8] = df.format(empStatsResBean.getOrdersAmount() / 10000) + "万";
				object[9] = nf.format(empStatsResBean.getOrdersTurnRate());
				object[10] = df.format(empStatsResBean.getInvestorUnitPrice() / 10000) + "万";
				exportList.add(object);
			}
			String[] columns = { "理财师", "团队", "投资人数", "成交投资人数", "客户转化率", "预约数", "外勤签到数", "成交订单数",
					"销售额", "订单转化率", "客单价" };
			int[] columnWidths = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 };
			ExportExcel exportExcel = new ExportExcel(columns, true, exportList);
			exportExcel.setColumnWidths(columnWidths);
			Workbook workbook = exportExcel.toExcel();

			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream; charset=UTF-8");
			String fileName = EMPLOYEE_STATS_REPORT + DateUtils.toDateString("yyyyMMddHHmmss");
			response.setHeader("Content-Disposition",
					"attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
			OutputStream os = response.getOutputStream();
			workbook.write(os);
			os.flush();
			os.close();
			workbook.close();
			response.flushBuffer();
		} catch (Exception e) {
			LOGGER.error("employeeStats downloadReportMonth error, msg=[{}]", e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 报表下载
	 * 
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@ResponseBody
	@RequestMapping("/downloadReportYear")
	public void downloadReportYear(HttpServletResponse response) {
		try {
			// 默认的时间
			Org org = orgServiceImpl.get(UserUtils.getOrgId());
			DateTime beginDateTime = new DateTime(org.getCreateTime());
			DateTime endDateTime = new DateTime(new Date());
			LOGGER.info("employeeStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			// 查询数据
			List<EmpStatsResBean> empStatsList = employeeStatsServiceImpl.queryEmployeeStatsMonth(
					beginDateTime, endDateTime, null, null);
			List<Object[]> exportList = new ArrayList<Object[]>();
			for (EmpStatsResBean empStatsResBean : empStatsList) {
				NumberFormat nf = NumberFormat.getPercentInstance();
				nf.setMinimumFractionDigits(2);
				nf.setRoundingMode(RoundingMode.HALF_UP);
				DecimalFormat df = new DecimalFormat("#0.00");
				Object[] object = new Object[11];
				object[0] = empStatsResBean.getName();
				object[1] = empStatsResBean.getGroupName();
				object[2] = empStatsResBean.getInvestorNum();
				object[3] = empStatsResBean.getDealInvestorNum();
				object[4] = nf.format(empStatsResBean.getInvestorTurnRate());
				object[5] = empStatsResBean.getAppointmentNum();
				object[6] = empStatsResBean.getCheckinNum();
				object[7] = empStatsResBean.getOrdersNum();
				object[8] = df.format(empStatsResBean.getOrdersAmount() / 10000) + "万";
				object[9] = nf.format(empStatsResBean.getOrdersTurnRate());
				object[10] = df.format(empStatsResBean.getInvestorUnitPrice() / 10000) + "万";
				exportList.add(object);
			}
			String[] columns = { "理财师", "团队", "投资人数", "成交投资人数", "客户转化率", "预约数", "外勤签到数", "成交订单数",
					"销售额", "订单转化率", "客单价" };
			int[] columnWidths = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 };
			ExportExcel exportExcel = new ExportExcel(columns, true, exportList);
			exportExcel.setColumnWidths(columnWidths);
			Workbook workbook = exportExcel.toExcel();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream; charset=UTF-8");
			String fileName = EMPLOYEE_STATS_REPORT + DateUtils.toDateString("yyyyMMddHHmmss");
			response.setHeader("Content-Disposition",
					"attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
			OutputStream os = response.getOutputStream();
			workbook.write(os);
			os.flush();
			os.close();
			workbook.close();
			response.flushBuffer();
		} catch (Exception e) {
			LOGGER.error("employeeStats downloadReportMonth error, msg=[{}]", e.getMessage());
			e.printStackTrace();
		}
	}
}
